package com.laxcen.basiclib.ui.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.githang.statusbar.StatusBarCompat;
import com.laxcen.basiclib.BaseConst;
import com.laxcen.basiclib.R;
import com.laxcen.basiclib.base.BaseActivity;
import com.laxcen.basiclib.core.bridgewebview.BridgeWebView;
import com.laxcen.basiclib.core.bridgewebview.api.DefaultApi;
import com.laxcen.basiclib.core.broadcast.BroadcastManager;
import com.laxcen.basiclib.core.permission.PermissionManager;
import com.laxcen.basiclib.core.updateH5.H5UpdateDialog;
import com.laxcen.basiclib.engine.ApiEngine;
import com.laxcen.basiclib.utils.CommonUtil;
import com.laxcen.basiclib.utils.FileUtil;

import java.util.HashMap;
import java.util.Map;

public class WebActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.white), true);
        PermissionManager.get(this).check(BaseConst.permission, () -> initWebview());
    }

    private BridgeWebView bridgeWebView;
    private BroadcastManager broadcastManager;
    //监听H5更新状态处理
    public static final String ON_WEB_UPDATE = "ON_WEB_UPDATE";
    private void initWebview(){
        bridgeWebView = findViewById(R.id.bridgeWebView);
        bridgeWebView.setWebContentsDebuggingEnabled(true);
        DefaultApi defaultApi = new DefaultApi(api);
        bridgeWebView.addJavascriptObject(defaultApi, null);
        String url = CommonUtil.getWebRoot(this);
        if(ApiEngine.h5AppConfig==null){
            String data = FileUtil.getFromRaw(mContext,R.raw.noconfig);
            bridgeWebView.loadDataWithBaseURL(null,data, "text/html",  "utf-8", null);
        }else{
            bridgeWebView.loadUrl(url);
        }

        api.checkUpdate();

        //监听更新状态
        broadcastManager = BroadcastManager.getInstance(mContext);
        broadcastManager.register(ON_WEB_UPDATE, new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String type = intent.getStringExtra("type");
                switch (type) {
                    case BaseConst.ACTION_DOWNLOADED_H5_UPLOAD:
                        //开始更新 弹出更新进度条
                        String path = intent.getStringExtra("path");
                        H5UpdateDialog.update(WebActivity.this, path);
                        break;
                    case BaseConst.ACTION_H5_UPLOADED:
                        //更新完 重新加载页面
                        api.loadH5Config(true);
                        String url = CommonUtil.getWebRoot(WebActivity.this);
                        bridgeWebView.loadUrl(url);
                        break;
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        broadcastManager.unregister(ON_WEB_UPDATE);
    }

    /**
     *  处理返回键
     */
    //这个字段用处在于 网页内部打开小窗口 点返回键只是想关闭小窗口而非整个页面
    //由web端控制，为false 当用户按了返回键时就通知web端处理
    private boolean canGoBack = true;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            String url = bridgeWebView.getUrl();
            if(!canGoBack){
                Map<String,Object> map = new HashMap<>();
                map.put("code",101);
                map.put("msg","用户按返回键");
                map.put("url",url);
                api.sendEventToWeb(map);
                return false;
            }
            //检查当前页是否注册可返回
            if(checkCan()){
                //如果是网页 可返回上一页就返回上一页
                if(bridgeWebView.canGoBack()){
                    bridgeWebView.goBack();
                }else{
                    //如果是首页再按就可以退出了
                    tobackHome();
                }
            }else{
                tobackHome();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 按两次回到桌面
     */
    private long exitTime = 0l;
    private void tobackHome(){
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            api.showToast("再按一次回到桌面");
            exitTime = System.currentTimeMillis();
        } else {
            moveTaskToBack(true);
        }
    }

    /**
     * 是否可以直接从当前返回桌面
     * true 否 false 是
     * @return
     */
    private boolean checkCan(){
        return !api.canBackToMain;
    }

}